#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

#define N 64

int main(int argc, char *argv[])
{
    // 0定义变量
    int sockfd;
    char buf[N];
    char readBuf[N];
    int addrlen = sizeof(struct sockaddr);
    struct sockaddr_in serveraddr;
    struct hostent *host;

    if(argc != 3){
        printf("usage: %s <domain> <port>\n", argv[0]);
        return -1;
    }

    host = gethostbyname(argv[1]);
    if(host == NULL) 
    {
        printf("error in gethostbyname:\n");
    }
    else
    {
        printf("name: %s\naddrtype; %d\naddrlength: %d\n",
            host->h_name, host->h_addrtype, host->h_length);
        printf("ip address: %s\n",
            inet_ntoa(*(struct in_addr*)host->h_addr_list[0]));
    }

    // 1创建一个套接字--socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        perror("socket err");
        exit(-1);
    }

    // 2指定服务器地址--sockaddr_in
    bzero(&serveraddr, addrlen);
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr = *((struct in_addr*)host->h_addr_list[0]);
    serveraddr.sin_port = htons(atoi(argv[2]));

    // 3连接服务器--connect
    if(connect(sockfd, (struct sockaddr *)&serveraddr, addrlen) < 0){
        perror("connect err");
        exit(-1);
    }

    // 4收发数据--recv/send
    while (1) {
        gets(buf);
        if(strcmp(buf, "quit") == 0){
            break;
        }
        send(sockfd, buf, N, 0);
        read(sockfd, buf, N);
        printf("buf = %s\n", buf);
    }

    // 5关闭连接--close
    close(sockfd);
}

